import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class TestUdpClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;
    public TestUdpClient(String serverIP,int serverPort) throws SocketException {
        socket = new DatagramSocket();

        this.serverPort = serverPort;
        this.serverIP = serverIP;
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("请输入要传递的信息:");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getData().length);
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        TestUdpClient testUdpClient = new TestUdpClient("127.0.0.1",9090);
        testUdpClient.start();
    }
}
